package com.ruoyi.common.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 向前端返回统一实体对象
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ResponseResult<T> {

    private Long code;
    private String message;
    private T data;

    /**
     * Ok
     */
    public static <T> ResponseResult ok(T data) {
        return new ResponseResult<>(200L,"",data);
    }
    public static  ResponseResult ok(){
        return new ResponseResult<>(200L,"",null);
    }

    /**
     * Error
     */
    public static  ResponseResult error(Long code, String message) {
        return new ResponseResult<>(code, message, null);
    }
    public static  ResponseResult error(Long code){
        return new ResponseResult<>(code, "", null);
    }

    /**
     * 发送JSON数据给前端
     */
    public static  void write(ResponseResult result, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        // 将对象转换为JSON字符串 jackson默认存在解析包
        String json = new ObjectMapper().writeValueAsString(result);
        // 将JSON通过输出流发送给前端
        response.getWriter().write(json);
        response.getWriter().close();
    }

}
